import 'package:flutter/cupertino.dart';
import 'package:specialty_no1/modules/http.dart';
/* {
    "_id" : ObjectId("5b2568a62a32561740a58504"),
    "pID" : 2001,
    "cID" : 2001,
    "addTime" : 1529178278304.0,
    "auctionId" : "570099131125",
    "title" : "琳媚 精致立体裁剪！气质名媛收腰荷叶边摆 精纺重磅丝羊毛连衣裙",
    "pictUrl" : "http://img.alicdn.com/bao/uploaded/i6/TB1YM0Wsh9YBuNjy0FfYXFIsVXa_M2.SS2",
    "shopTitle" : "琳媚",
    "zkPrice" : 1636,
    "biz30day" : 28,
    "tkRate" : 5,
    "tkCommFee" : 81.8,
    "nick" : "smay88888",
    "shortLinkUrl" : "https://s.click.taobao.com/JVQIdPw",
    "clickUrl" : "https://s.click.taobao.com/t?e=m%3D2%26s%3DP97WNkm0mokcQipKwQzePOeEDrYVVa64LKpWJ%2Bin0XLjf2vlNIV67oRepdR61Sx7jGYPrSmetxGq7Af1%2B1nxixrdZ2eNeZs4PORD%2FJ%2FY7xL3W%2FF8zo5yTQ%2FXNgfQgPYT4c8l9GiG59L9gQqZb0jtChnh345iShLoxg5p7bh%2BFbQ%3D",
    "taoToken" : "€mKzE0Cf2TmV€",
    "couponTotalCount" : 10000,
    "couponLeftCount" : 8991,
    "couponAmount" : 30,
    "couponEffectiveStartTime" : "2018-04-10",
    "couponEffectiveEndTime" : "2018-07-09",
    "couponLink" : "https://uland.taobao.com/coupon/edetail?e=W%2B3A44hIOp%2FzX1yJ4zwwthspBnyu0x2lFbj9mqvjUqHcdxT1K8BUOTPmd%2F1fxTqKQ%2B36NT4S7W5mMaSWOIN1zgPbfjxGQb3QrWFtGDBhQ58%3D&af=1&pid=mm_42989648_13138110_69734237",
    "couponLinkTaoToken" : "€ZKfR0Cf2973€",
    "couponShortLinkUrl" : "https://s.click.taobao.com/CLvShPw"
} */

/// 商品数据处理
/// 网络请求数据
/// 通常需要与[Provider]插件一起使用
class GoodsModel extends ChangeNotifier {
  int _sort = 1;
  int _pageNum = 1;
  int _prePageNum = 1;
  String _keyword;
  List data = [];
  int get pageNum => _pageNum;

  /// 设置排序并请求数据及更新页面
  /// [1]是综合
  /// [2]是销售
  /// [3]是价格
  /// 设置多个值
  Future<void> setValue({int sort, int pageNum, String keyword}) async {
    if (sort != null) {
      _sort = sort;
    }
    if (pageNum != null) {
      // 记录上次的页码
      _prePageNum = _pageNum;
      _pageNum = pageNum;
    }
    if (keyword != null) {
      _keyword = keyword;
    }
    await _request();
  }

  // 请求数据
  Future<void> _request({bool isPush = false}) async {
    var res = await http.post('/goods/search', data: {"q": _keyword, "sort": _sort.toString(), "pageNum": _pageNum});
    // 如果页码比上次的大就累加商品数据
    if (_prePageNum < _pageNum) {
      this.data = List.from(this.data)..addAll(res.data);
    } else {
      this.data = res.data;
    }
    notifyListeners();
  }

  /// 刷新数据
  Future<void> refresh() async {
    // 复原数据
    this.data = [];
    _pageNum = 1;
    _prePageNum = 1;
    await _request();
  }
}
